<template>
  <div>
    <el-card>

      <el-alert title="添加商品信息" type="info" center show-icon>
      </el-alert>

      <!-- step 区域 -->
      <el-steps :space="200" align-center :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab 区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="tabsLeave" @tab-click="tabsClick">
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <br/>
              <el-cascader
                v-model="addForm.goods_cat"
                :options="options"
                :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children'}"
                @change="handleChange"></el-cascader>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item, i1) in paramsData" :key="item.attr_name">
              <br>
              <el-tag v-for="(tag, i2) in item.attr_vals" :key="tag" closable @close="removeTag(i1, i2)">
                {{tag}}
              </el-tag>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item :label="item.attr_name" v-for="(item, i) in attrData" :key="i">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <el-upload
              :action="uploadURL"
              :headers="picHeaders"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods" class="btn-add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog
      title="预览"
      :visible.sync="dialogVisible"
      width="50%">
      <img :src="previewPath" alt="" class="preview-img">
    </el-dialog>
  </div>
</template>

<script>
import { apiAddGoods, apiGetCategories, apiGetCateAttributes } from '@/api/index.js'
// 文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import _ from 'lodash'

export default {
  name: 'add',
  created () {
    this.getCateList()
  },
  data () {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      // 表单
      addFormRules: {
        'goods_name': [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        'goods_price': [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        'goods_weight': [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        'goods_number': [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        'goods_cat': [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]

      },
      // 所有 商品分类数据
      options: [],
      // 商品参数
      paramsData: [],
      // 商品属性
      attrData: [],
      // 上传图片
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      picHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      fileList: [],
      // 图片预览
      dialogVisible: false,
      previewPath: ''
    }
  },
  methods: {
    addGoods () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请将信息填写完整')
        }
        console.log('通过验证')
        const form = _.cloneDeep(this.addForm)
        // 处理 静态属性 数据
        this.attrData.forEach(item => {
          form.attrs.push({
            'attr_id': item.attr_id,
            'attr_value': item.attr_vals
          })
        })
        // 分类列表
        form.goods_cat = form.goods_cat.join(',')
        // 处理 动态参数 数据
        this.paramsData.forEach(item => {
          form.attrs.push({
            'attr_id': item.attr_id,
            'attr_value': item.attr_vals.join(' ')
          })
        })
        console.log(form)

        const { data: res } = await apiAddGoods(form)
        if (res.meta.status !== 201) {
          return this.$message.error(`${res.meta.status}: ${res.meta.msg}`)
        }
        this.$message.success('操作成功')
        this.$router.push('/goods')
      })
    },
    // 获取 category 信息
    async getCateList () {
      const { data: res } = await apiGetCategories()
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.options = res.data
    },
    // 商品分类 切换
    handleChange () {
      if (!this.cateId) {
        this.$message.error('请选择三级分类的商品分类')
        this.addForm.goods_cat = []
        return false
      }
    },
    // 切换tab 前 回调
    tabsLeave (activeName, oldActiveName) {
      if (oldActiveName === '0') {
        if (!this.cateId) {
          this.$message.error('请选择商品分类')
          return false
        }
      }
    },
    // 点击切换 tab
    tabsClick () {
      if (this.activeIndex === '1') {
        this.getCateAttr('many')
      } else if (this.activeIndex === '2') {
        this.getCateAttr('only')
      }
    },
    // 获取 动态参数/静态属性
    async getCateAttr (type) {
      let id = this.addForm.goods_cat[2]
      const { data: res } = await apiGetCateAttributes(id, { sel: type })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status + ' ' + res.meta.msg
        )
      }
      if (type === 'many') {
        res.data.forEach(item => {
          item.attr_vals = (item.attr_vals === '' ? [] : item.attr_vals.split(' '))
        })
        this.paramsData = res.data
      } else if (type === 'only') {
        this.attrData = res.data
      }
    },
    // 移除标签
    removeTag (i1, i2) {
      console.log(i1, i2)
      this.paramsData[i1].attr_vals.splice(i2, 1)
    },
    // 上传图片 相关函数
    handleRemove (file, fileList) {
      const filePath = file.response.data.tmp_path
      let i = this.addForm.pics.findIndex(x => x === filePath)
      this.addForm.pics.splice(i, 1)
    },
    handlePreview (file) {
      this.dialogVisible = true
      this.previewPath = file.url
    },
    handleSuccess (response, file, fileList) {
      if (response.meta.status !== 200) {
        return this.$message.error(`${response.meta.status}: ${response.meta.msg}`)
      }
      this.addForm.pics.push({
        'pic': response.data.tmp_path
      })
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  components: {
    quillEditor
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 0 10px 0 0 !important;
  }

  .preview-img {
    width: 100%;
  }

  .btn-add {
    margin-top: 15px;
  }
</style>
